package router

import (
	_ "MessageSendService/app/api/docs"
	"MessageSendService/app/api/internal/controller"
	"MessageSendService/app/common/log"
	"github.com/gin-gonic/gin"
	swaggerfiles "github.com/swaggo/files"
	_ "github.com/swaggo/gin-swagger"
	ginSwagger "github.com/swaggo/gin-swagger"
	"go.uber.org/zap"
	"time"
)

func Router() *gin.Engine {
	r := gin.New()

	r.Use(corsMiddleware())
	r.Use(ginLogger(log.GetZapOriginLogger())) //设置gin的log为自定义的logger
	r.Use(gin.Recovery())

	//注册模版类型的接口
	controller.TemplateInit(r)
	controller.AccountInit(r)
	r.GET("/swagger/*any", ginSwagger.WrapHandler(swaggerfiles.Handler))

	//注册消息类型的结构

	r.GET("/message", controller.Message{}.Hello)

	//发送一条信息
	r.POST("/message/send", controller.Message{}.Send)

	return r
}

// 自定义的CORS中间件
func corsMiddleware() gin.HandlerFunc {
	return func(c *gin.Context) {
		c.Writer.Header().Set("Access-Control-Allow-Origin", "*")
		c.Writer.Header().Set("Access-Control-Allow-Credentials", "true")
		c.Writer.Header().Set("Access-Control-Allow-Headers", "Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization, accept, origin, Cache-Control, X-Requested-With")
		c.Writer.Header().Set("Access-Control-Allow-Methods", "POST, OPTIONS, GET, PUT, DELETE")

		if c.Request.Method == "OPTIONS" {
			c.AbortWithStatus(204)
			return
		}

		c.Next()
	}
}

// GinLogger 接收gin框架默认的日志
func ginLogger(logger *zap.Logger) gin.HandlerFunc {
	return func(c *gin.Context) {
		start := time.Now()
		path := c.Request.URL.Path
		query := c.Request.URL.RawQuery
		c.Next()

		cost := time.Since(start)
		logger.Info(path,
			zap.Int("status", c.Writer.Status()),
			zap.String("method", c.Request.Method),
			zap.String("path", path),
			zap.String("query", query),
			zap.String("ip", c.ClientIP()),
			zap.String("user-agent", c.Request.UserAgent()),
			zap.String("errors", c.Errors.ByType(gin.ErrorTypePrivate).String()),
			zap.Duration("cost", cost),
		)
	}
}
